﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using WFNetLib.Log;
using WFNetLib.TCP;
using WFNetLib.PacketProc;
using System.Net.Sockets;
using System.IO;
using WFNetLib;
using System.Security.Cryptography;
//using Vincent.WebConfigManager;

namespace 数据接口
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }                
        private void Form1_Load(object sender, EventArgs e)
        {           
            toolStripButton1.Text = "停止定时采集";
            timer1_Tick(null, null);
            timer1.Enabled = true;
            timer2_Tick(null, null);
            timer2.Enabled = true;   
        }
        TcpModbusPacket ModbusWork(byte[] tx,TcpModbusPacket.FunctionCode type)
        {
            string str;
            TCPSyncClient tcp = new TCPSyncClient();
            tcp.TCPServerName ="10.103.4.106";
            tcp.SaveDataProcessCallback = new SaveDataProcessCallbackDelegate(TcpModbusPacket.SaveDataProcessCallbackProc);
            tcp.TCPServerPort = 502;
            //ShowText("-----------------------"+DateTime.Now.ToLocalTime()+"------------------------");
            if (!tcp.Conn())
            {
                str = "无法连接到服务器:";
                if (tcp.LastException.GetType() == typeof(SocketException))
                {
                    SocketException ex = (SocketException)tcp.LastException;
                    switch (ex.ErrorCode)
                    {
                        case 10061:
                            str += ex.Message;
                            break;
                        case 10060:
                            str += ex.Message;
                            break;
                    }
                }
                else
                    str = "未知错误:" + tcp.LastException.Message;
                ShowText(str);
                return null;
            }
            ShowText("发送数据:" + WFNetLib.Strings.StringsFunction.byteToHexStr(tx, " "));
            byte[] txBytes = TcpModbusPacket.MakePacket(0, 0, type, tx);
            if (!tcp.SendPacket(txBytes))
            {
                return null;
            }
            object o = tcp.ReceivePacket();
            if (o == null)
            {
                ShowText("未收到需要读取的数据");
                return null;
            }
            TcpModbusPacket tp = (TcpModbusPacket)o;
            ShowText("收到数据:" + WFNetLib.Strings.StringsFunction.byteToHexStr(tp.Data, " "));
            tcp.Close();
            return tp;
        }
        int Delta;
        bool bAdjusted;
        private void timer1_Tick(object sender, EventArgs e)
        {
            string str;
            try
            {
                if (VerifySoft())
                {
                    timer1.Enabled = false;
                    ShowText("闸杆数据定时周期到", true);
                    byte[] tx = new byte[4];
                    tx[0] = 0x00;//起始地址
                    tx[1] = 0xd4;
                    tx[2] = 0;//长度
                    tx[3] = 2;
                    TcpModbusPacket tp = ModbusWork(tx, TcpModbusPacket.FunctionCode.Read);
                    if (tp == null)
                    {
                        ShowText("闸杆数据未接收到PLC数据");
                        return;
                    }
                    UInt16 s1 = BytesOP.MakeShort(tp.Data[1], tp.Data[2]);
                    UInt16 s2 = BytesOP.MakeShort(tp.Data[3], tp.Data[4]);
                    string str1, str2;
                    str1 = "";
                    str2 = "";
                    string[][] d = new string[2][];
                    d[0] = new string[11];
                    d[1] = new string[11];
                    for (int i = 0; i < 11; i++)
                    {
                        if (BytesOP.GetBit(s1, i))
                            str1 += "1";
                        else
                            str1 += "0";
                    }
                    for (int i = 0; i < 11; i++)
                    {
                        if (BytesOP.GetBit(s2, i))
                            str2 += "1";
                        else
                            str2 += "0";
                    }
                    WebReference.TaxiWebServiceService l = new WebReference.TaxiWebServiceService();
                    l.sayHello(str1, str2);
                }
            }
            catch (System.Exception ex)
            {
                ShowText("闸杆数据发生错误:" + ex.Message);
            }
            finally
            {
                timer1.Enabled = true; ;
            }
        }
        private delegate void ShowTextLog(string str, bool newSection);
        private void ShowTextLogProc(string str ,bool newSection)
        {
            if (textBox1.Text.Length > 20000)
                textBox1.Clear();
            if(newSection)
                textBox1.AppendText("---------------------" + DateTime.Now.ToString("yy年MM月dd日 hh:mm:ss") + "-------------------\r\n");
            textBox1.AppendText(str+"\r\n");
            TextLog.AddTextLog(str,newSection);
        }
        public void ShowText(string str, bool newSection)
        {
            this.Invoke(new ShowTextLog(ShowTextLogProc), str,newSection);
        }
        public void ShowText(string str)
        {
            this.Invoke(new ShowTextLog(ShowTextLogProc), str,false);
        }
        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            if (toolStripButton1.Text == "开始定时采集")
            {
                toolStripButton1.Text = "停止定时采集";
                timer1.Enabled = true;
                timer2.Enabled = true;
            }
            else
            {
                toolStripButton1.Text = "开始定时采集";
                timer1.Enabled = false;
                timer2.Enabled = false;
            }
        }

        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            WebReference.TaxiWebServiceService l = new WebReference.TaxiWebServiceService();
            l.sayHello("10101010101", "01010101010");
            
//             byte[] tx = new byte[200+5];
//             tx[0] = 0x00;//起始地址
//             tx[1] = 0xd5;
//             tx[2] = 0;//长度
//             tx[3] = 100;
//             tx[4] = 200;//写入字节数
//             for(int i=0;i<200;i++)
//                 tx[i+5] = (byte)i;
//             //tx[6]=(byte)20;
//             ModbusWork(tx, TcpModbusPacket.FunctionCode.Write);
        }

        private void toolStripButton3_Click(object sender, EventArgs e)
        {
            byte[] tx = new byte[4];
            tx[0] = 0x00;//起始地址
            tx[1] = 0xd4;
            tx[2] = 0;//长度
            tx[3] = 2;
            TcpModbusPacket tp= ModbusWork(tx, TcpModbusPacket.FunctionCode.Read);            
        }

        private void timer2_Tick(object sender, EventArgs e)
        {
            string str;
            try
            {
                if(VerifySoft())
                {
                    timer2.Enabled = false;
                    ShowText("车辆数量定时周期到", true);
                    byte[] tx = new byte[4];
                    tx[0] = 0x00;//起始地址
                    tx[1] = 0xe9;
                    tx[2] = 0;//长度
                    tx[3] = 4;
                    TcpModbusPacket tp = ModbusWork(tx, TcpModbusPacket.FunctionCode.Read);
                    if (tp == null)
                    {
                        ShowText("车辆数量未接收到PLC数据");
                        return;
                    }
                    byte[] bb = new byte[4];
                    bb[3] = tp.Data[3];
                    bb[2] = tp.Data[4];
                    bb[1] = tp.Data[1];
                    bb[0] = tp.Data[2];
                    int f1 = BitConverter.ToInt32(bb, 0);
                    bb[3] = tp.Data[7];
                    bb[2] = tp.Data[8];
                    bb[1] = tp.Data[5];
                    bb[0] = tp.Data[6];
                    int f2 = BitConverter.ToInt32(bb, 0);

                    WebReference.TaxiWebServiceService l = new WebReference.TaxiWebServiceService();
                    l.circleData(f1, f2);
                }
            }
            catch (System.Exception ex)
            {
                ShowText("车辆数量发生错误:" + ex.Message);
            }
            finally
            {
                timer2.Enabled = true; ;
            }
        }
        bool VerifySoft()
        {
            const string VerifyVersion = "wfHXSJJK";
            SoftVerifyData svd;
            try
            {
                svd = SoftVerify.GetVerifyData(VerifyVersion);
            }
            catch (CryptographicException ex)//数据被更改
            {
                ShowText("数据接口程序的致命错误:"+ex.Message);
                return false;
            }
            DateTime ldt = new DateTime(2015, 7, 5);
            if (DateTime.Now > ldt)
            {
                ShowText("数据接口程序的试用到期，请永久激活");
                return false;
            }
            if (svd.UsedDays > 130)
            {
                ShowText("数据接口程序的试用到期，请永久激活");
                return false;
            }
            else
            {
                DateTime cur=DateTime.Now;
                if (svd.CurTime.AddDays(1) < DateTime.Now || svd.CurTime > DateTime.Now)
                {
                    svd.UsedDays++;
                    svd.CurTime = DateTime.Now;
                }                
            }
            if(svd.UsedTimes>100000)
            {
                ShowText("数据接口程序的试用到期，请永久激活");
                return false;
            }
            else
            {
                svd.UsedTimes++;
            }
            SoftVerify.SetVerifyData(VerifyVersion, svd);
            return true;
        }
    }
}
